/*
 * Copyright (C) 2008 GeoScheduler Team, as stated on <http://www.geoscheduler.org/authors>.
 * 
 * This file is part of GeoScheduler.
 * 
 * GeoScheduler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * GeoScheduler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with GeoScheduler. If not, see <http://www.gnu.org/licenses/>.
 */
package org.geoscheduler.commons.qbuilder;

import java.util.Iterator;
import java.util.Map;

import org.geoscheduler.commons.qbuilder.TableDecl.ColumnDecl;

/**
 * FIXME [lko] comment me!
 *
 * @author lko
 */
public class WhereSQLBuilder extends AbstractSQLBuilder<WhereSQLBuilder> {

	public WhereSQLBuilder() {
		this(new StringBuilder());
	}

	public WhereSQLBuilder(StringBuilder bld) {
		super(bld);
		append("WHERE ");
	}

	public WhereSQLBuilder nPredicate(String junction, ColumnDecl<?,?>... column) {
		int len = column.length - 1;
		for (int i = 0; i <= len; i++) {
			nPredicate(column[i]);
			if (i < len) {
				append(" ").append(junction).append(" ");
			}
		}
		return this;
	}

	public WhereSQLBuilder nPredicate(String junction, Map<String, String> columns) {
		for (Iterator<Map.Entry<String, String>> eIt = columns.entrySet().iterator(); eIt.hasNext();) {
			Map.Entry<String, String> entry = eIt.next();
			nPredicate(entry.getKey(), entry.getValue());
			if (eIt.hasNext()) {
				append(" ").append(junction).append(" ");
			}
		}

		return this;
	}
	
	public WhereSQLBuilder predicate(String junction, Map<String, String> columns) {
		for (Iterator<Map.Entry<String, String>> eIt = columns.entrySet().iterator(); eIt.hasNext();) {
			Map.Entry<String, String> entry = eIt.next();
			predicate(entry.getKey(), entry.getValue());
			if (eIt.hasNext()) {
				append(" ").append(junction).append(" ");
			}
		}

		return this;
	}

	public WhereSQLBuilder nPredicate(ColumnDecl<?,?> column) {
		return nPredicate(column.name(), column.name());
	}

	public WhereSQLBuilder predicate(String name, String value) {
		append(name).append("=").append(value);
		return this;
	}

	public WhereSQLBuilder nPredicate(String name, String mapping) {
		append(name).append("=:").append(mapping);
		return this;
	}

	public WhereSQLBuilder and() {
		return append(" AND ");

	}

	public WhereSQLBuilder or() {
		return append(" OR ");
	}
}
